// pages/person/present/index.js
const ajax = require('../../../utils/quest.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    max: 300, //最多字数 (根据自己需求改变) 
    currentWordNumber: 0,
    picList: [],
    arrList: [],
    animation: {},
    showModalStatus: false,
    checkedData: 0,
    cateSubList: [{
        id: 0,
        categoryName: '农机'
      },
      {
        id: 1,
        categoryName: '农机'
      },
      {
        id: 2,
        categoryName: '农机'
      },
      {
        id: 3,
        categoryName: '农机'
      },
    ],
    cateList: [],
    selectList: [],
    name: '', //姓名
    phone: '', //联系电话
    specialty: '', //专业
    region: [], //地址
    unitRegion: [],
    unitPictureLits: [],
    unitList: [],
    ossUrl: '',
    personalPhotolist: [],
    unitPhotoList: [],
    userInfo: '',
    selectLists: [],
    displayUserInfo: {},
    personalInformation: {},
    userInfoId: {},
    myRegionId: undefined,
    unitRegionId: {},
    adressArr:[],
    unitRegion:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      ossToken: app.globalData.ossToken,
    })
    this.getTree()
  },
  //字数限制 
  inputs: function (e) {
    // 获取输入框的内容
    var value = e.detail.value;
    // 获取输入框内容的长度
    var len = parseInt(value.length);
    this.setData({
      currentWordNumber: len //当前字数 
    });
    //最多字数限制
    if (len > this.data.max) return;
    // 当输入框内容的长度大于最大长度限制（max)时，终止setData()的执行
  },
  // 我的地址
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var adressArr = e.detail.value;
    if (adressArr[1] == '北京市' || adressArr[1] == '天津市' || adressArr[1] == '上海市' || adressArr[1] == '重庆市') {
      adressArr[1] = '市辖区'
    }
    this.getArea(adressArr.join(","), 0);
    this.setData({
      region: e.detail.value,
      adressArr: adressArr
    })
    console.log(this.data.region);
  },
  // 工作地址
  bindUnitChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var adressArr = e.detail.value;
    if (adressArr[1] == '北京市' || adressArr[1] == '天津市' || adressArr[1] == '上海市' || adressArr[1] == '重庆市') {
      adressArr[1] = '市辖区'
    }
    this.getArea(adressArr.join(','), 1);
    this.setData({
      // unitRegion: e.detail.value.join(''),
      unitRegion:adressArr
    })
  },
  getArea: function (strUrl, type) {
    var that = this;
    var strUrls = {
      names: strUrl
    }
    ajax.sendRequest("/area/getAreaByNames", 'get', strUrls)
      .then(function (response) {
        var resArr = response.data.areaVOS;
        if (resArr.length >= 3) {
          var province = response.data.areaVOS[0].value;
          var city = undefined;
          var district = undefined;
          for (var i = 0; i < resArr.length; i++) {
            if (resArr[i].pid == province) {
              city = resArr[i].value;
            }
            if (resArr[i].pid == city) {
              district = resArr[i].value;
            }

          }
          var regionId = {
            province: province,
            city: city,
            district: district
          }
          // type 0的时候是我的地址
          if (type == 0) {
            console.log("type", type);
            console.log('regionId', regionId);
            that.setData({
              myRegionId: regionId
            })
          } else {
            that.setData({
              unitRegionId: regionId
            })
          }

        } else if (resArr.length == 0) {
          wx.showModal({
            title: '提示',
            content: '该平台目前不支持您所选区域！',
          })
        }
      }, function (error) {})
  },
  // 上传
  uploadImages: function () {
    const than = this
    const {
      arrList,
      personalPhotolist
    } = than.data
    console.log('arrList', arrList);
    console.log('personalPhotolist', personalPhotolist);

    wx.chooseImage({
      count: 1,
      sizeType: ['original'], //原图
      sourceType: ['album', 'camera'], //支持选取图片
      success(res) {
        arrList.push(res.tempFiles[0])
        ajax.upLoadFiles(res.tempFiles[0].path).then(res => {
          // const imgUrl = res
          const personalPhoto = {
            'picUrl': res
          }
          personalPhotolist.push(personalPhoto)
          if (res) {
            than.setData({
              picList: arrList,
              personalPhotolist: personalPhotolist
            })
          } else {
            return wx.showToast({
              title: '系统内部错误，请联系管理员',
              icon: 'none',
            })
          }
        })
      }
    })
  },
  upLoadFiles() {
    const {
      ossToken
    } = this.data
    wx.uploadFile({
      filePath: this.data.picList[0].path,
      name: 'file',
      url: ossToken.host,
      success: (res) => {
        console.log("resssssssss", res);
      },
      fail: (err) => {
        console.log('err', err);
      }
    })
  },
  // 删除
  delImages: function (e) {
    const {
      personalPhotolist
    } = this.data
    console.log(personalPhotolist);
    const that = this
    const index = e.currentTarget.dataset.item
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          personalPhotolist.splice(index, 1)
          that.setData({
            personalPhotolist: personalPhotolist
          })
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
      }
    })

  },
  // 上传
  doUpload() {
    const than = this
    const {
      unitPictureLits,
      unitPhotoList
    } = than.data
    wx.chooseImage({
      count: 1,
      sizeType: ['original'], //原图
      sourceType: ['album', 'camera'], //支持选取图片
      success(res) {
        unitPictureLits.push(res.tempFiles[0])
        ajax.upLoadFiles(res.tempFiles[0].path).then(res => {
          // const imgUrl = res
          const unitPhoto = {
            'picUrl': res
          }
          unitPhotoList.push(unitPhoto)
          if (res) {
            than.setData({
              unitList: unitPictureLits,
              unitPhotoList: unitPhotoList
            })
          } else {
            return wx.showToast({
              title: '系统内部错误，请联系管理员',
              icon: 'none',
            })
          }
        })

      }
    })
  },
  //删除
  delPicture(e) {
    const {
      unitPhotoList
    } = this.data
    const that = this
    const index = e.currentTarget.dataset.item
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          unitPhotoList.splice(index, 1)
          that.setData({
            unitPhotoList: unitPhotoList
          })
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
      }
    })
  },
  bandSpecialty: function () {
    this.showModal()
  },
  // 显示对话框
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  addressRelicList: function (e) {
    let id = e.currentTarget.dataset.id;
    console.log("id", id);
    let item = this.data.cateList.map(i => {
      const idItem = i.sonCategoryList.filter(j => {
        return j.id == id
      })
      return idItem
    })
    console.log("item", item);
    const {
      selectList
    } = this.data
    for (var k = 0; k < item.length; k++) {
      item[k].map(i => {
        i.isSelected = !i.isSelected
        if (i.isSelected == true) {
          selectList.push(i)
        }
      })
    }
    console.log("xuanz ", selectList);
    this.setData({
      cateList: this.data.cateList,
      selectList: selectList
    })
  },
  getTree: function () {
    ajax.sendRequest('/category/getCategoryTree', 'get').then(res => {
      const {
        categoryVOList
      } = res.data
      const isList = []
      for (var i = 0; i < categoryVOList.length; i++) {
        for (var j = 0; j < categoryVOList[i].sonCategoryList.length; j++) {
          // console.log(categoryVOList[i].sonCategoryList[j]);
          categoryVOList[i].sonCategoryList[j].isSelected = false
        }
        isList.push(categoryVOList[i])
      }
      this.setData({
        cateList: isList,
      })
    })
  },
  formSubmitLogin(e) {
    this.setData({
      personalInformation: e.detail.value
    })
    console.log('e.detail.value', e.detail.value);
    const {
      userInfoId
    } = this.data
    userInfoId.id ? this.modify() : this.save()
  },
  // 获取用户信息
  getFarmerUserInfo() {
    ajax.sendRequest('/farmer/farmerUserInfo', 'get').then(res => {
      console.log("用户信息", res);
      const userInfo = res.data.farmerInformationVO

      if (!userInfo) {
        return
      }
      console.log("userInfo", userInfo);
      const {
        cateList
      } = this.data
      const categoryIds = (userInfo || userInfo.categoryIds) == null ? [] : userInfo.categoryIds // 后台选中的id
      // console.log("(userInfo || userInfo.categoryIds)", (userInfo || userInfo.categoryIds));
      console.log("userInfo.categoryIds", categoryIds);
      for (var k = 0; k < cateList.length; k++) {
        cateList[k].sonCategoryList.forEach(i => {
          if (categoryIds) {
            categoryIds.forEach(j => {
              if (j == i.id) {
                i.isSelected = true
              }
            });
          }
        })
      }
      this.setData({
        userInfoId: userInfo,
        fullName: userInfo.fullName,
        telephone: userInfo.telephone,
        categoryIds: userInfo.categoryIds,
        specialty: userInfo.major,
        address: userInfo.address,
        synopsis: userInfo.introduce,
        region: [userInfo.provinceName, userInfo.cityName, userInfo.districtName],
        unitRegion: userInfo.unitInformationVO && userInfo.unitInformationVO.provinceName ? [userInfo.unitInformationVO.provinceName, userInfo.unitInformationVO.cityName, userInfo.unitInformationVO.districtName, ] : [],
        companyName: userInfo.unitInformationVO ? userInfo.unitInformationVO.unitName : '',
        unitAddress: userInfo.unitInformationVO ? userInfo.unitInformationVO.address : '',
        unitIntroduce: userInfo.unitInformationVO ? userInfo.unitInformationVO.introduce : null,
        unitPhotoList: userInfo.unitInformationVO.unitPicList,
        personalPhotolist: userInfo.userPicList,
        cateList: this.data.cateList
      })
    })
  },
  bandCancel() {
    this.hideModal()
  },
  bandDetermine() {
    const {
      selectList,
      cateList,
    } = this.data
    console.log("确定后的数据", cateList);

    // console.log('selectList', selectList);
    // const list = cateList.map(i => {
    //   console.log("i", i);
    //   const idItem = i.sonCategoryList.filter(j => {
    //     return j.isSelected == true
    //   })
    //   return idItem
    // })
    const selectLists = []
    for (var k = 0; k < cateList.length; k++) {
      console.log("cateList", cateList[k]);
      cateList[k].sonCategoryList.map(i => {
        if (i.isSelected == true) {
          selectLists.push(i)
        }
      })
      console.log("1231", selectLists);
    }
    const categoryIds = selectLists.map(item => {
      return item.id
    })
    const categoryName = selectLists.map(item => {
      return item.categoryName
    })
    console.log(categoryName);
    this.setData({
      specialty: categoryName.join(','),
      cateList: cateList,
      categoryIds: categoryIds
    })
    this.hideModal()
  },
  // 保存函数
  save() {
    const that = this
    const {
      myRegionId,
      unitRegionId,
      personalPhotolist,
      unitPhotoList,
      specialty,
      personalInformation,
      selectList,
      adressArr,
      unitRegion
    } = this.data
    const major = selectList.map(item => {
      return item.id
    })
    console.log("myRegionId", myRegionId);
    if (!personalInformation.fullName) {
      return wx.showToast({
        icon: "none",
        title: '请填写真实姓名',
      })
    } else if (!personalInformation.telephone) {
      return wx.showToast({
        icon: "none",
        title: '请填写联系电话',
      })
    } else if (!specialty) {
      return wx.showToast({
        icon: "none",
        title: '请选择选择专业',
      })
    } else if (!myRegionId) {
      return wx.showToast({
        icon: "none",
        title: '请选择选择地址',
      })
    } else if (!personalInformation.companyName) {
      console.log("1进来了", );
      if (personalInformation.unitRegion.length > 0 || personalInformation.unitAddress || personalInformation.unitIntroduce || unitPhotoList.length > 0) {
        console.log("22222");
        return wx.showToast({
          icon: "none",
          title: '请填写单位名称',
        })
      }
    }
    console.log("333");
    const reqBody = {
      fullName: personalInformation.fullName,
      telephone: personalInformation.telephone,
      major: specialty, //专业
      categoryIds: major, //专业id
      address: personalInformation.address,
      ...myRegionId, //省市区
      userPicList: personalPhotolist,
      introduce: personalInformation.synopsis,
      unitInformation: {
        ...unitRegionId,
        unitName: personalInformation.companyName,
        address: personalInformation.unitAddress,
        introduce: personalInformation.unitIntroduce,
        provinceName:unitRegion[0],
        cityName:unitRegion[1],
        districtName:unitRegion[2],
      },
      unitPicList: unitPhotoList,
      
      provinceName:adressArr[0],
      cityName:adressArr[1],
      districtName:adressArr[2],
      // position: region

    }
    ajax.sendRequest('/farmer/saveFarmerUserInfo', 'post', reqBody).then(res => {
      console.log('保存', res);
      wx.showModal({
        title: '提示',
        content: '保存成功',
      })
      that.getFarmerUserInfo()
    })

  },
  // 修改函数
  modify() {
    const that = this
    const {
      myRegionId,
      personalPhotolist,
      unitRegionId,
      unitPhotoList,
      specialty,
      personalInformation,
      categoryIds,
      userInfoId,
      selectLists,
      region,
      adressArr,
      unitRegion
      // specialty,
      // myRegionId
    } = that.data
    if (!personalInformation.fullName) {
      return wx.showToast({
        icon: "none",
        title: '请填写真实姓名',
      })
    } else if (!personalInformation.telephone) {
      return wx.showToast({
        icon: "none",
        title: '请填写联系电话',
      })
    } else if (!specialty) {
      return wx.showToast({
        icon: "none",
        title: '请选择选择专业',
      })
    } else if (!personalInformation.companyName) {
      console.log("1进来了", personalInformation.companyName);
      if (personalInformation.unitRegion.length || personalInformation.unitAddress || personalInformation.unitIntroduce || unitPhotoList.length) {
        console.log("222222222");
        return wx.showToast({
          icon: "none",
          title: '请填写单位名称',
        })
      }
    }
    const reqBody = {
      id: userInfoId.id,
      fullName: personalInformation.fullName,
      telephone: personalInformation.telephone,
      major: specialty, //专业
      categoryIds: categoryIds, //专业id
      address: personalInformation.address,
      ...myRegionId, //省市区
      userPicList: personalPhotolist,
      introduce: personalInformation.synopsis,
      unitInformation: {
        ...unitRegionId,
        id: userInfoId.unitInformationVO ? userInfoId.unitInformationVO.id : null,
        unitName: personalInformation.companyName,
        address: personalInformation.unitAddress,
        introduce: personalInformation.unitIntroduce,
        provinceName:unitRegion[0],
        cityName:unitRegion[1],
        districtName:unitRegion[2],
      },
      unitPicList: unitPhotoList,
      provinceName:adressArr[0],
      cityName:adressArr[1],
      districtName:adressArr[2],
    }
    console.log("reqBody", reqBody);
    ajax.sendRequest('/farmer/saveFarmerUserInfo', 'post', reqBody).then(res => {
      console.log('保存', res);
      wx.showModal({
        title: '提示',
        content: '修改成功',
        success: function (res) {
          if (res.confirm) {
            that.getFarmerUserInfo()
          } else {
            console.log('取消')
          }
        }
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getFarmerUserInfo()

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})